import axios from 'axios';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:5000',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
instance.interceptors.request.use(
  config => {
    try {
      const userStore = useUserStore();
      const token = userStore.token;
      
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      
      return config;
    } catch (error) {
      console.error('Error in request interceptor:', error);
      return config;
    }
  },
  error => {
    console.error('Request error:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  response => response,
  error => {
    try {
      if (error.response?.status === 401) {
        const userStore = useUserStore();
        userStore.logout();
        ElMessage.error('登录已过期，请重新登录');
      }
    } catch (err) {
      console.error('Error in response interceptor:', err);
    }
    return Promise.reject(error);
  }
);

export default instance; 